package zhihuilan.controlle.wechatMini;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import zhihuilan.common.Response;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.enums.ResultEnum;
import zhihuilan.common.utils.HttpUtils;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.config.StaticFiledConfig;
import zhihuilan.config.WxMiniConfig;
import zhihuilan.controlle.BasicController;
import zhihuilan.entity.MySms;
import zhihuilan.entity.MyStaff;
import zhihuilan.entity.MyUser;
import zhihuilan.entity.tools.WxSessionResult;
import zhihuilan.mapper.MySmsMapper;
import zhihuilan.params.query.RegisterQueryParam;
import zhihuilan.service.MyMemberService;
import zhihuilan.service.MySmsService;
import zhihuilan.service.MyStaffService;
import zhihuilan.service.MyUserService;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;

/**
 * 小程序端API </p>
 * 接口说明：</p>
 *
 * @Module 系统基础用户接口模块
 * @Author chenk
 * @Version 1.0.1 (2025-02-24)
 */
@Slf4j
@RestController
@RequestMapping("/app/account")
public class AccountController extends BasicController {
    Logger logger = Logger.getLogger(AccountController.class.getName());
    @Autowired
    private WxMiniConfig wxMiniConfig;

    @Resource
    private StaticFiledConfig myStaffConfig;

    @Resource
    private MyStaffService myStaffService;

    @Resource
    private MyUserService myUserService;

    @Resource
    private MyMemberService myMemberService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private MySmsService mySmsService;

    /**
     * 登录或者注册小程序账号
     *
     * @param queryParam  基础用户【RegisterQueryParam】标准查询参数类；
     * @return 标准响应体封装基础登录信息返回数据
     * @ApiNote 支持基础信息与扩展信息组合查询
     * @Author chenk
     * @Version 1.0.1
     */
    @PostMapping("/register")
    public WxMiniResponse register(@RequestBody RegisterQueryParam queryParam) {
        if (ObjectUtils.isEmpty(queryParam.getCode())) {
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(), "缺少code");
        }
        if (!ToolsUtils.isMobile(queryParam.getTelephone())) {
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(), "请授权获取手机号");
        }
        String url = wxMiniConfig.getJscodeUrl() + "?appid=" + wxMiniConfig.getAppId() + "&secret=" + wxMiniConfig.getAppSecret() + "&js_code=" + queryParam.getCode() + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        WxSessionResult wxSessionResult = JSON.parseObject(result, WxSessionResult.class);
        if (ObjectUtils.isEmpty(wxSessionResult)) {
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(), "参数错误");
        }
        MyStaff staff = myStaffService.selectMyStaffByTel(queryParam.getTelephone());
        String resultGuid = "";
        Random random = new Random();
        if (ObjectUtils.isEmpty(staff)) {
            staff = new MyStaff();
            staff.setTelephone(queryParam.getTelephone());
            staff.setOpenid(wxSessionResult.getOpenid());
            staff.setOpenid2(wxSessionResult.getOpenid());
//            staff.setNickname("微信用户"+random.nextInt());
            staff.setHeadimgurl(myStaffConfig.getDefaultAvatar());
            if (ObjectUtils.isEmpty(queryParam.getFid())) {
                staff.setFid(0);
            } else {
                staff.setFid(queryParam.getFid());
            }
            long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
            if (!ObjectUtils.isEmpty(queryParam.getChannel())) {
                MyUser user = myUserService.selectUserByChannel(queryParam.getChannel());
                if (!ObjectUtils.isEmpty(user)) {
                    staff.setInvitecode(user.getId() + "");
                }
                staff.setOutinvitetime(Integer.parseInt(timestamp + 7776000 + ""));
            } else {
                String invitecode = myMemberService.selectMaxInvitecode();
                staff.setInvitecode(ObjectUtils.isEmpty(invitecode) ? "" : invitecode);
            }
            staff.setAddtime(new Date());
            staff.setAudit(1);
            //用户保存成功之后，获取到保存成功的ID，用于计算其他字段数据并更新；
            staff = myStaffService.addEntity(staff);
        } else {
            staff.setOpenid(wxSessionResult.getOpenid());
            staff.setOpenid2(wxSessionResult.getOpenid());
            staff.setFid(queryParam.getFid());
            staff = myStaffService.updateEntity(staff);
        }
        resultGuid = staff.getGuid();

        return WxMiniResponse.ok(resultGuid);
    }

    /**
     * 根据用户选择的电话号码code，返回用户选择的电话号码明文号码；
     *
     * @param queryParam  基础用户【RegisterQueryParam】标准查询参数类，传入参数为电话号码[telephone]；
     * @return 标准响应体封装转换后的电话号码；
     * @ApiNote 使用时候区分开发环境和生产环境，开发环境中使用注释下的代码；生产环境的时候，请使用开发环境上面的代码；
     * @Author chenk
     * @Version 1.0.1
     */
    @PostMapping("/getPhonenumberByCode")
    public WxMiniResponse getPhonenumberByCode(@RequestBody RegisterQueryParam queryParam) throws UnsupportedEncodingException, WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject j = new JSONObject();
        j.put("code", queryParam.getCode());
        String result = HttpUtils.sendPost(url, j.toString());
        return WxMiniResponse.ok(JSONObject.parseObject(result));

        // 以下是开发环境用的返回数据；
//        Map<String, Object> map = new HashMap<>();
//        Map<String, Object> map2 = new HashMap<>();
//        map2.put("phoneNumber", "13774347464");
//        map.put("phone_info", map2);
//        return WxMiniResponse.ok(map);
    }

    /**
     *   account/registerByCode  手机验证登录或者注册APP账号
     *
     * @param  String  code 验证码;
     * @param  String telephone 电话号码;
     * @return 标准响应体封装基础登录信息返回数据
     * @ApiNote 支持基础信息与扩展信息组合查询
     */
    @PostMapping("/registerByCode")
    public WxMiniResponse getRegisterOrLoginByCode(@RequestBody RegisterQueryParam queryParam){
        System.out.println(queryParam);
        if(!ToolsUtils.isMobile(queryParam.getTelephone())){
            return WxMiniResponse.error(2013, "请输入正确手机号码");
        }
        if(ObjectUtils.isEmpty(queryParam.getCode())){
            return WxMiniResponse.error(2013, "请输入正确验证码");
        }
        MySms mySms = new MySms();
        mySms.setTelephone(queryParam.getTelephone());
        mySms.setCode(queryParam.getCode());
        if(mySmsService.verifysms(mySms)){
            MyStaff staff =  myStaffService.selectMyStaffByTel(queryParam.getTelephone());
            String resultGuid = "";
            if (ObjectUtils.isEmpty(staff)) {
                staff = new MyStaff();
                staff.setTelephone(queryParam.getTelephone());
                staff.setHeadimgurl(myStaffConfig.getDefaultAvatar());
                if (ObjectUtils.isEmpty(queryParam.getFid())) {
                    staff.setFid(0);
                } else {
                    staff.setFid(queryParam.getFid());
                }
                long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
                if (!ObjectUtils.isEmpty(queryParam.getChannel())) {
                    MyUser user = myUserService.selectUserByChannel(queryParam.getChannel());
                    if (!ObjectUtils.isEmpty(user)) {
                        staff.setInvitecode(user.getId() + "");
                    }
                    staff.setOutinvitetime(Integer.parseInt(timestamp + 7776000 + ""));
                } else {
                    String invitecode = myMemberService.selectMaxInvitecode();
                    staff.setInvitecode(ObjectUtils.isEmpty(invitecode) ? "" : invitecode);
                }
                staff.setAddtime(new Date());
                staff.setAudit(1);
                //用户保存成功之后，获取到保存成功的ID，用于计算其他字段数据并更新；
                staff = myStaffService.addEntity(staff);
            } else {
                staff.setLasttime(Integer.parseInt(new Date().getTime()/1000+""));
                staff = myStaffService.updateEntity(staff);
            }
            resultGuid = staff.getGuid();
            return WxMiniResponse.ok(resultGuid);
        }
        return WxMiniResponse.error(2013,"请输入正确的验证码！");
    }


}
